package com.ruicar.afs.cloud.admin.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.admin.api.dto.DeptDto;
import com.ruicar.afs.cloud.admin.service.SysDepartmentService;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.admin.entity.SysDepartment;
import com.ruicar.afs.cloud.admin.entity.SysUser;
import com.ruicar.afs.cloud.admin.service.SysUserService;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 *
 */
@Slf4j
@RestController
@Api(description = "部门管理接口")
@RequestMapping("/department")
@CacheConfig(cacheNames = "department")
public class SysDepartmentController {

	@Autowired
	private SysDepartmentService sysDepartmentService;

	@Autowired
	private SysUserService userService;

	@RequestMapping(value = "/getByParentId/{parentId}", method = RequestMethod.GET)
	@ApiOperation(value = "通过id获取")
	public IResponse<List<SysDepartment>> getByParentId(@PathVariable String parentId) {
		return new IResponse<List<SysDepartment>>().setData(setInfo(sysDepartmentService.findByParentIdOrderBySortOrder(parentId)));
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ApiOperation(value = "添加")
	@SysLog("添加部门")
	@Transactional
	public IResponse<Boolean> add(@RequestBody SysDepartment department) {
		sysDepartmentService.save(department);
		SysDepartment sysDepartment = sysDepartmentService.getById(department.getParentId());
		if(sysDepartment!=null) {
			sysDepartment.setIsParent(Boolean.TRUE);
			sysDepartmentService.updateById(sysDepartment);
		}
		return new IResponse<Boolean>().setMsg("添加成功").setData(true);
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	@ApiOperation(value = "编辑")
	@SysLog("编辑部门")
	@Transactional
	public IResponse<Boolean> edit(@RequestBody SysDepartment department) {
		sysDepartmentService.updateById(department);
		return new IResponse<Boolean>().setMsg("编辑成功").setData(true);
	}

	@RequestMapping(value = "/delByIds/{ids}", method = RequestMethod.DELETE)
	@ApiOperation(value = "批量通过id删除")
	@SysLog("批量通过id删除部门")
	@Transactional
	public IResponse<Boolean> delByIds(@PathVariable String[] ids) {

		for (String id : ids) {
			List<SysUser> list = userService.list(Wrappers.<SysUser>query().lambda().eq(SysUser::getDeptId, id));
			if (list != null && list.size() > 0) {
				return new IResponse<Boolean>().setCode(CommonConstants.FAIL).setMsg("删除失败，包含正被用户使用关联的部门").setData(false);
			}
		}
		Arrays.stream(ids).forEach(id -> {
			sysDepartmentService.remove(Wrappers.<SysDepartment>update().lambda().eq(SysDepartment::getParentId, id));
			sysDepartmentService.removeById(id);
		});

		return new IResponse<Boolean>().setMsg("批量通过id删除数据成功").setData(true);
	}

	@RequestMapping(value = "/search", method = RequestMethod.GET)
	@ApiOperation(value = "部门名模糊搜索")
	public IResponse<List<SysDepartment>> searchByTitle(@RequestParam String title) {
		List<SysDepartment> list = sysDepartmentService.findByTitleLikeOrderBySortOrder(title);
		list = setInfo(list);
		return new IResponse<List<SysDepartment>>().setData(list);
	}

	@PostMapping(value = "/getDeptInfoById/{id}")
	public IResponse<DeptDto> getDeptInfoById(@PathVariable Long id) {
		SysDepartment sysDepartment = sysDepartmentService.getById(id);
		if(sysDepartment==null){
			throw new AfsBaseException(CommonConstants.FAIL,"指定部门不存在");
		}
		DeptDto deptDto = new DeptDto();
		deptDto.setId(sysDepartment.getId());
		deptDto.setTitle(sysDepartment.getTitle());
		return IResponse.success(deptDto);
	}


	public List<SysDepartment> setInfo(List<SysDepartment> list) {

		// lambda表达式
		list.forEach(item -> {
			if (!CommonConstants.PARENT_ID.equals(Long.valueOf(item.getParentId()))) {
				SysDepartment parent = sysDepartmentService.getById(Long.valueOf(item.getParentId()));
				item.setParentTitle(parent.getTitle());
			} else {
				item.setParentTitle("一级部门");
			}
		});
		return list;
	}
}
